import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
import router from "@/router";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
});
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 注入token
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${encodeURIComponent(
        store.getters.token
      )}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    console.log(response);
    if (response.data instanceof Blob) return response.data;
    // 请求成功 但是状态码不是200 提示错误信息
    if (response.data.code !== 200) {
      Message({ type: "error", message: response.data.msg });
      return Promise.reject(new Error(response.data.msg));
    }
    return response.data;
  },
  async (error) => {
    // 处理token失效
    if (error.response.status === 401) {
      Message({ type: "warning", message: "token超时了" });
      await store.dispatch("user/logout");
      router.push("/login");
      return Promise.reject(error);
    }
    Message({ type: "error", message: error.msg });
    return Promise.reject(error);
  }
);

export default service;
